import { Component, OnInit, Input, Output, EventEmitter} from '@angular/core';


@Component({
  selector: 'el-cascader-panel',
  templateUrl: './cascader-panel.component.html',
  
})
export class CascaderPanelComponent implements OnInit {
  @Input() options:any = [];
  @Input() props:any = {};
  @Input() value:any = '';
  @Input() model:any = '';
  @Input() border:boolean = false;
  @Input() menuVisible:boolean = true;
  @Input() steps:any=[];
  @Output('change') modelChange: EventEmitter<any> = new EventEmitter();
  @Output('expand-change') expandChange: EventEmitter<any> = new EventEmitter();
  @Input() currentLabels: Array<any> = [];
  @Input('change-on-select') changeOnSelect: boolean = false;
  
  childrenName = 'children';
  labelName = 'label';
  valueName = 'value';
  constructor() { 
  }

  ngOnInit(): void {
    this.steps[0] = this.options;
    console.log(this.options)
    
    if(this.props && this.props['label']){
      this.labelName = this.props['label'];
    }

    if(this.props && this.props['value']){
      this.valueName = this.props['value'];
    }


    if(this.props && this.props['children']){
      this.childrenName = this.props['children'];
    }

    if(this.value) {
      this.model = this.value;
    }
  }
  

  selectHandle(event: Event, step: number, index: number): any {
    event.stopPropagation()

    if (this.steps[step][index].disabled) return
  
    this.steps[step] = this.steps[step].map((item: any, i: number) =>{
      return  Object.assign(item, { active: i === index })
    });
   
    // reset steps
    this.steps.length = step + 1
    const next = this.steps[step][index][this.childrenName]

    this.expandChangeLabels();
    // go next
    if (next && Array.isArray(next)) {
      // change on select (props)
      this.changeOnSelect && this.changeLabels()
      
      const nativeNext = next.map((item: any) => Object.assign(item, { active: false }))
      // console.log(event, step, index,this.steps);
      
      return this.steps.push(nativeNext);
    }
    
    // last step
    this.changeLabels()
    this.menuVisible = false
  }


  changeLabels(): void {
    const nextValue: any = []
    
    this.steps.forEach((items: any[]) => {
      const steps: any[] = items.filter((item: any) => item.active)
      nextValue.push(steps[0])
    })
    this.currentLabels = nextValue
    const next = nextValue.map((item: any) => item[this.valueName])
    this.model = next
    this.steps[0] = this.steps[0].map((item: any) => Object.assign(item, { active: false }));
    this.modelChange.emit(next)
  }

  expandChangeLabels() {
    const nextValue: any[] = []
    
    this.steps.forEach((items: any[]) => {
      const steps: any[] = items.filter((item: any) => item.active)
      nextValue.push(steps[0])
    })
    const next = nextValue.map((item: any) => item[this.valueName]);
    
    this.expandChange.emit(next)
  }
}